package com.dong.HashMap.arithemtic;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author dcz
 * @classname Demo4
 * @description 两数之和
 * @date 2022/4/20 10:18
 */
public class Demo4 {
    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        int target = 18;
        int[] ints = twoSum(nums, target);
        System.out.println(Arrays.toString(ints));
    }

    //双指针
    public static int[] twoSum(int[] nums, int target) {
        int slowIndex = 0;
        int length = nums.length;
        int[] result = new int[2];
        while (slowIndex<length-1){
            for (int quickIndex = slowIndex+1 ; quickIndex < length; quickIndex++) {
                if (nums[slowIndex]+nums[quickIndex]==target){
                    result[0] = slowIndex;
                    result[1] = quickIndex;
                }
            }
            ++slowIndex;
        }
        return result;
    }


    //利用HashMap
    public int[] twoSum2(int[] nums, int target) {
        int[] res = new int[2];
        if (nums == null || nums.length == 0){
            return res;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)){
                res[1] = i;
                res[0] = map.get(temp);
            }
            map.put(nums[i],i);
        }
        return res;
    }

}
